package com.xmlt.core.template;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;

public class TemplateParameter {

	private String name;
	private boolean isMultiple;
	private ParamTypes type;
	private String ref;
	private TemplateManager manager;
	private boolean isValid = true;
	private TemplateException error;

	public TemplateParameter(Element el, TemplateManager tm) {
		name = el.getAttribute("name");
		isMultiple = "true".equalsIgnoreCase(el.getAttribute("multiple"));
		String typeString = el.getAttribute("type");
		if ("value".equalsIgnoreCase(typeString)) {
			type = ParamTypes.VALUE;
		} else if ("link".equalsIgnoreCase(typeString)) {
			type = ParamTypes.LINK;
		} else if ("reference".equalsIgnoreCase(typeString)) {
			type = ParamTypes.REFERENCE;
		}
		ref = el.getAttribute("ref");
		manager = tm;
	}

	public String toString() {
		String s = "";
		s += (isMultiple ? "multiple" : "single") + " "
				+ (type == ParamTypes.VALUE ? "value" : "link") + " param: "
				+ name + " (" + ref + ")";
		return s;
	}

	public String getName() {
		return name;
	}

	protected ParamTypes getType() {
		return type;
	}

	public boolean isLink() {
		return getType() == ParamTypes.LINK;
	}
	
	public boolean isValue() {
		return getType() == ParamTypes.VALUE;
	}
	
	public boolean isReference() {
		return getType() == ParamTypes.REFERENCE;
	}

	public String getReference() {
		return ref;
	}

	public boolean isMultiple() {
		return isMultiple;
	}

	public void setIsValid(boolean flag) {
		isValid = flag;
	}

	public void setError(TemplateException e) {
		error = e;
	}

	public boolean isValid() {
		return isValid;
	}

	public TemplateException getError() {
		return error;
	}

	public Template getTemplate() throws TemplateException {
		if (!(isLink() || isReference()) || !isValid)
			return null;

		return manager.findTemplate(ref);
	}

	public void generateParameterInInstanceNode(Node n) {
		Document d = null;
		if (n.getNodeType() == Node.DOCUMENT_NODE) {
			d = (Document) n;
		} else {
			d = n.getOwnerDocument();
		}
		Element paramterEl = d.createElement("parameter");
		n.appendChild(paramterEl);

		paramterEl.setAttribute("name", getName());
		if (isMultiple()) {
			
		} else {
			if (isLink()) {
				String paramRef = getReference();
				try {
					Template reftemplate = manager.findTemplate(paramRef);
					reftemplate.generateChildInstances(paramterEl);
				} catch (TemplateException e) {
					setError(e);
					setIsValid(false);
				}
			} else if (isReference()) {
				Element instanceRefElement = d.createElement("instance");
				paramterEl.appendChild(instanceRefElement);
			}
		}
	}
}
